﻿

using System.Linq;
using System.Web.Mvc;
using Wabo.Dal.Interface;
using Wabo.Web.Areas.Manager.Core;
using Wabo.Web.Areas.Manager.Core.Attributes;
using Wabo.Web.Areas.Manager.ViewModels.Acl;

namespace Wabo.Web.Areas.Manager.Controllers
{
    [UserAuthorized]
    public class AclController : WaboController
    {        
        [ModuleListPermission]
        [ModuleReadPermission]
        public ActionResult Index()
        {            
            LogEvent(LogOperation.View);
            return View();
        }        

        [ModuleListPermission]
        [ModuleWritePermission]
        [ModuleDeletePermission]        
        public ActionResult GroupAcl(long id)
        {
            // List group's module permissions

            var g = GroupContext.Get(id);
            if (g == null)
                return RedirectToAction("Index", "Group");            
            ViewBag.GroupName = g.name;
            var model = new AclViewModel();
            var aclList = ModuleContext.Modules.Select(m => new AclItem
                {
                    Group = g, 
                    Module = m, 
                    List = ModuleContext.GroupCanList(g, m), 
                    Read = ModuleContext.GroupCanRead(g, m), 
                    Write = ModuleContext.GroupCanWrite(g, m), 
                    Delete = ModuleContext.GroupCanDelete(g, m)
                }).ToList();
            model.AclItems = aclList;
            LogEvent(LogOperation.Modify, string.Format("Group:{0} ", g.name));
            return View(model);
        }

        [HttpPost]
        [ModuleListPermission]
        [ModuleWritePermission]
        [ModuleDeletePermission]        
        public ActionResult GroupAcl(AclViewModel model)
        {
            // Set group's module permissions
            if (ModelState.IsValid)
            {
                foreach (var aclItem in model.AclItems)
                {
                    Dal.Group g = GroupContext.Get(aclItem.Group.id);
                    if (g != null)
                    {

                        const string logDescriptionFormat = "Group:{0} Module:{1} List:{2} Read:{3} Write{4} Delete:{5}";
                        var logDescription = string.Format(logDescriptionFormat, g.name, aclItem.Module.title,
                                                           aclItem.List, aclItem.Read, aclItem.Write, aclItem.Delete);
                        LogEvent(LogOperation.Modify, logDescription);

                        ModuleContext.SetModuleGroupPermissions(g,aclItem.Module,aclItem.List,aclItem.Read,aclItem.Write,aclItem.Delete);
                    }
                }
                return RedirectToAction("Index", "Group");
            }
            return View(model);
        }
    }
}
